
# -*- coding:utf-8 -*-
#"F:\code\git\Dynamic method V1.3\MainControl_Firmware\0-prj\APP\Objects\APP.bin" "..\BOOT\Objects\boot.bin" 0x20000
import os, sys
import struct
import hashlib
version_path = "../1-user/version.h"

if not os.path.exists(version_path):
    print('ERROR: not find %s!' % version_path)
    sys.exit(1)

version_file = open(version_path, 'r', encoding='utf-8')

device_info = ""
DEVICE_NAME = ""
BOARD_NAME = ""
HARDWARE_VERSION = ""
SOFTWARE_VERSION = ""
PROJECT_TIME = ""

while True:
    line = version_file.readline()
    if not line:
        break
    else:
        
        start_addr = line.find("#define BOARD_NAME	")
        if start_addr != -1:
            BOARD_NAME = line.split('"')[1]   
                   
        if "#define DEVICE_NAME" in line:
            DEVICE_NAME = line.split('"')[1]
            print(DEVICE_NAME)
            print(line)
            continue
             
        start_addr = line.find("#define HARDWARE_VERSION ")
        if start_addr != -1:
            HARDWARE_VERSION = line.split('"')[1]            
              
        start_addr = line.find("#define SOFTWARE_VERSION ")
        if start_addr != -1:
            SOFTWARE_VERSION = line.split('"')[1]


                                      
version_file.close()

# device_item = device_info.split('-')

# if len(device_item) != 7:
#     print("ERROR: device info format error!")
#     sys.exit(1)

device_info = "E-%s-%s-%s-%s" % (DEVICE_NAME, BOARD_NAME, HARDWARE_VERSION, SOFTWARE_VERSION)
old_bin_path = sys.argv[1]
# old_bin_path = r"F:\code\git\Dynamic method V1.3\MainControl_Firmware\0-prj\APP\Objects\APP.bin"
new_bin_path = 'E-%s-%s-%s-%s.bin' % (DEVICE_NAME, BOARD_NAME, HARDWARE_VERSION, SOFTWARE_VERSION)

old_bin_file = open(old_bin_path, 'rb')
new_bin_file = open(new_bin_path, 'wb')

bin_data = old_bin_file.read()

new_bin_file.write(device_info.encode('utf-8'))

for i in range(128-len(device_info)):
    s = struct.pack('b', 0)
    new_bin_file.write(s)

sha256_hash = hashlib.sha256(bin_data).digest()
new_bin_file.write(sha256_hash)
new_bin_file.write(len(bin_data).to_bytes(length=4,byteorder='little',signed=False))
new_bin_file.write(bin_data)

print("device info: " + device_info)
print("bin file size: " + str(len(bin_data)))
print("file path: " + new_bin_path)

old_bin_file.close()
new_bin_file.close()
